package io.renren.modules.truck.controller.admin;

import io.renren.common.exception.RRException;
import io.renren.common.utils.C;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/file")
public class FileController {


    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (!file.isEmpty()) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
            String saveFileName = file.getOriginalFilename();
            //获取文件后缀
            String suffix = getSuffix(saveFileName);
            String hou = suffix + "/" + sdf.format(new Date()) + "/" + System.currentTimeMillis() + "_" + saveFileName;
            String path = C.upload_windows + hou;

            System.out.println(path);
            File saveFile = new File(path);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                String savePath = "fileSystem/" + hou;

                String webPath = request.getRequestURL().toString().replace("file/upload", "");

                return R.ok().put("path", savePath);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return R.error("上传失败," + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                return R.error("上传失败," + e.getMessage());
            }
        } else {
            return R.error("上传失败，因为文件为空.");
        }
    }

    public String uploadEdit(MultipartFile file, HttpServletRequest request) throws Exception {
        if (!file.isEmpty()) {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
            String saveFileName = file.getOriginalFilename();
            //获取文件后缀

            String suffix = getSuffix(saveFileName);
            String hou = suffix + "/" + sdf.format(new Date()) + "/" + System.currentTimeMillis() + "_" + saveFileName;
            String path = C.upload_windows + hou;

            System.out.println(path);
            File saveFile = new File(path);
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }

            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
            out.write(file.getBytes());
            out.flush();
            out.close();
            String savePath = "fileSystem/" + hou;

            String webPath = request.getRequestURL().toString().replace("file/editor/upload", "");
            System.out.println(request.getRequestURI());
            System.out.println(request.getRequestURL());
            System.out.println(request.getServletPath());


            return webPath + savePath;

        } else {
            throw new RRException("上传失败，因为文件为空");
        }
    }

    private String getSuffix(String saveFileName) {
        String[] su = saveFileName.split("\\.");
        String rs = su[su.length - 1];
        System.out.println("文件后缀:" + rs);
        return rs;
    }

    /**
     * 富文本编辑器中上传图片功能
     *
     * @param list
     * @return
     */
    @PostMapping(value = "/editor/upload")
    public Map<String, Object> upload(@RequestParam("file") List<MultipartFile> list, HttpServletRequest request) {

        Integer errno = 0;
        List<String> urls = new ArrayList<>();
        Map<String, Object> map = new HashMap<>(2);

        if (list.size() == 0) {
            errno = 1;
        }

        for (MultipartFile file : list) {
            // 此处调用自己的上传文件方法
            String url = null;
            try {
                url = this.uploadEdit(file, request);
            } catch (Exception e) {
                errno = 2;
                e.printStackTrace();
            }
            if (!StringUtil.isNullBoolean(url)) {
                urls.add(url);
            } else {
                System.out.println("富文本编辑器上传图片失败，文件名：{}");
                errno = 2;
            }
        }

        map.put("errno", errno);
        map.put("data", urls);
        return map;
    }

    /**
     * 多文件上传  没有测试
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        File savePath = new File(request.getSession().getServletContext().getRealPath("/upload/"));
        if (!savePath.exists()) {
            savePath.mkdirs();
        }
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    File saveFile = new File(savePath, file.getOriginalFilename());
                    stream = new BufferedOutputStream(new FileOutputStream(saveFile));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    if (stream != null) {
                        stream.close();
                        stream = null;
                    }
                    return "第 " + i + " 个文件上传有错误" + e.getMessage();
                }
            } else {
                return "第 " + i + " 个文件为空";
            }
        }
        return "所有文件上传成功";
    }
}